package com.ada.jodd;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.List;

public class JsonUtil {

    public static <T> List<T> toJson(String body, Class<T> className){
        List<T> result=null;
        ObjectMapper mapper = getObjectMapper();
        try {
            JavaType javaType = mapper.getTypeFactory().constructParametricType(List.class, className);
            result = mapper.readValue(body, javaType);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
    public static String toJson(Object object){
        ObjectMapper mapper = getObjectMapper();
        String jsonString = null;
        try {
            jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return jsonString;
    }
    public static <T> T object(String body,Class<T> className){
       T result=null;
        ObjectMapper mapper = getObjectMapper();
        try {
            result = mapper.readValue(body, className);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
    public static ObjectMapper getObjectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        return mapper;
    }
}
